#coding=utf-8
#LightCam 远程管理程序
#init by hfh 20150212

import socket,time,re,sys,traceback,os

def switch(argv,value):

	if argv=='comd':
		s.sendall("__StartOfTheCommand__")
		lag=1
		sd=''
		while lag:
			res=s.recv(BUFSIZ)
			if re.match("__ReadyForTheCommand__",res):
				s.sendall(value+"__EndOfTheCommand__")
				continue
			sd=sd+res
			res=re.findall(r"__EndOfTheResult__",sd,re.S)
			if len(res) <> 0:
				sd=sd.replace("__EndOfTheResult__","")
				s.close()
				print str(sd)
				lag=0
			sd=sd+str(res).strip('[]')

	if argv=='ecmd':
		s.sendall("__StartOfEstablishedCommand__")
		lag=1
		sd=''
		while lag:
			time.sleep(0.1)
			res=s.recv(BUFSIZ)
			
			if re.match("__ReadyForEstablishedCommand__",res):
				s.sendall(value+"__EndOfEstablishedCommand__")
				continue
			sd=sd+res
			res=re.findall(r"__EndOfTheResult__",sd,re.S)
			if len(res) <> 0:
				sd=sd.replace("__EndOfTheResult__","").strip('\n\r ').strip('[]')
				print "%s" % sd
				s.close()
				lag=0

	if argv=='eget':
		fargv=value.split('__')
		if len(fargv)<3:
			s.close()
			print "please input agentname, localfile and remotefile"
			return 0
		agentname=fargv[0]
		localfile=fargv[1]
		remotefile=fargv[2]
		
		msg="__StartOfEstablishedGetFile__%s__%s__%s__" % (agentname,localfile,remotefile)
		s.sendall(msg)
		while True:
			time.sleep(0.1)
			recv_data=''
			try:
				res=s.recv(BUFSIZ)
			except:
				pass
			if re.match("__FileNotExist__",res):
				s.close()
				logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
				print logdate+',文件'+remotefile+'读取失败'
				return 0
			if re.match("__FileNoContent__",res):
				s.close()
				logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
				print logdate+',文件'+remotefile+'为空'
			elif re.match("__BUFSIZS__",res):
				s.sendall('__ReadyForEstablishedGetFile__')
				filesize=re.findall(r"__BUFSIZS__(.*)__BUFSIZE__",res,re.S)
				logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
				print logdate+",准备下载文件"+remotefile
				print logdate+",文件大小为"+str(filesize[0])
				if len(filesize)==0:
					s.close()
					logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
					print logdate+",文件大小为空"
					s.sendall('__EndForEstablishedGetFile__')
					return 0
				else:
					filesize=int(filesize[0])
					s.sendall("__ReadyForEstablishedGetFile__")
					recv_data=''
					rfilesize=filesize
					fileoper = open(localfile,'wb')
					while True:
						time.sleep(0.001)
						recv_datas=''
						if rfilesize>BUFSIZ:
							recv_datas = s.recv(BUFSIZ)
						else:
							recv_datas = s.recv(filesize)
						fileoper.write(recv_datas)
						rfilesize=rfilesize-len(recv_datas)
						pert=100-100*rfilesize/filesize
						if pert > 100.0:
							pert=100.0
						print "\r "+str(pert)+"%",
						#sys.stdout.write("\r"+str(pert)+"%",)
						#sys.stdout.flush()
						if rfilesize<=0:
							break
					fileoper.flush()
					fileoper.close()
					logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
					print "\n%s,文件下载成功,已保存到[%s]" % (logdate,localfile)
					#print logdate+",文件下载成功,已保存到"+localfile
					#s.sendall('__EndForEstablishedGetFile__')
					s.close()
					break

	if argv=='eput':
		fargv=value.split('__')
		if len(fargv)<3:
			s.close()
			print "please input agentname, localfile and remotefile"
			return 0
		agentname=fargv[0]
		localfile=fargv[1]
		remotefile=fargv[2]
		if os.path.isfile(localfile):
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			print logdate+',准备发送文件'+localfile
		else:
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			print logdate+',文件'+localfile+'不存在'
			s.close()
			return 0
		
		fileoper=open(localfile,'rb')
		filesize=os.path.getsize(localfile)
		
		msg="%s__%s__%s__StartOfEstablishedPutFile__" % (agentname,filesize,remotefile)
		s.sendall(msg)
		#s.sendall("__StartOfPutFile__"+"__AgentName__"+str(agentname)+"__AgentName__"+"__FileSize__"+str(filelength)+"__FileSize__"+"__FileName__"+str(remotefile)+"__FileName__")

		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		print logdate+',文件大小为'+str(filesize)
		
		while True:
			time.sleep(0.1)
			res=s.recv(BUFSIZ)
			if re.findall("__ReadyForEstablishedPutFile__",res):
				rfilesize=filesize
				while True:
					time.sleep(0.001)
					send_datas=''
					if rfilesize>BUFSIZ:
						send_datas = fileoper.read(BUFSIZ)
					else:
						send_datas = fileoper.read(rfilesize)
					s.sendall(send_datas)
					rfilesize=rfilesize-len(send_datas)
					pert=round(100.0-100.0*rfilesize/filesize,2)
					if pert > 100.0:
						pert=100.0
					print "\r "+str(pert)+"%",
					if rfilesize<=0:
						break
				fileoper.close()
				#s.sendall('__EndForEstablishedPutFile__')
				#break
			#if re.findall("__EndForEstablishedPutFile__",res):
				s.close()
				logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
				print "\n%s,文件上传成功,已保存到[%s]" % (logdate,remotefile)
				#print logdate+",文件上传成功,已保存到"+remotefile
				break
				

	if argv=='InitArgvs':
		s.sendall("__InitArgvs__")
		lag=1
		sd=''
		while lag:
			time.sleep(0.1)
			res=s.recv(BUFSIZ)
			print res
			if re.match("__InitArgvs__",res):
				print "argvs init success"
				break
				
	if argv=='InitAgentList':
		s.sendall("__InitAgentList__")
		lag=1
		sd=''
		while lag:
			time.sleep(0.1)
			res=s.recv(BUFSIZ)
			print res
			if re.match("__InitAgentList__",res):
				print "agent list init success"
				break


	if argv=='stopagent':
		s.sendall("__StopAgent__")
		lag=1
		sd=''
		while lag:
			time.sleep(0.1)
			res=s.recv(BUFSIZ)
			print res
			if re.match("__ReadyToStopAgent__",res):
				s.close()
				lag=0
				print "Agent Stopped"
		
	elif argv=='put':
		fargv=value.split()
		if len(fargv)<2:
			s.close()
			print "please input localfile and remotefile"
			return 0
		localfile=fargv[0]
		remotefile=fargv[1]
		if os.path.isfile(localfile):
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			print logdate+',准备发送文件'+localfile
		else:
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			print logdate+',文件'+localfile+'不存在'
			s.close()
			return 0
		
		fileoper=open(localfile,'rb')
		filedata=fileoper.read()
		filelength=len(filedata)
		fileoper.close()
		
		s.sendall("__StartOfPutFile__"+"__BUFSIZS__"+str(filelength)+"__BUFSIZE__"+"__FILENAMES__"+str(remotefile)+"__FILENAMEE__")

		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		print logdate+',文件大小为'+str(filelength)
		
		res=s.recv(BUFSIZ)
		if re.match("__ReadyForPutFile__",res):
			s.sendall(filedata)
		lag=1
		while lag:
			res=s.recv(BUFSIZ)
			if re.match("__EndForPutFile__",res):
				s.close()
				logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
				print logdate+",文件上传成功,已保存到"+remotefile
				lag=0
			time.sleep(0.1)
			
	elif argv=='get':
		fargv=value.split()
		if len(fargv)<2:
			s.close()
			print "please input remotefile and localfile"
			return 0
		remotefile=fargv[0]
		localfile=fargv[1]
		
		s.sendall("__StartOfGetFile__"+"__FILENAMES__"+str(remotefile)+"__FILENAMEE__")
		lag=1
		while lag:
			recv_data=''
			try:
				res=s.recv(BUFSIZ)
			except:
				pass
			if re.match("__FileNotExist__",res):
				s.close()
				logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
				print logdate+',文件'+remotefile+'读取失败'
				return 0
			elif re.match("__BUFSIZS__",res):
				filesize=re.findall(r"__BUFSIZS__(.*)__BUFSIZE__",res,re.S)
				logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
				print logdate+",准备下载文件"+remotefile
				print logdate+",文件大小为"+str(filesize[0])
				if len(filesize)==0:
					s.close()
					logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
					print logdate+",文件大小为空"
					return 0
				else:
					filesize=int(filesize[0])
					s.sendall("__ReadyForGetFile__")
					
					recv_data=''
					rfilesize=filesize
					fileoper = open(localfile,'wb')
					while True:
						recv_datas=''
						if rfilesize>BUFSIZ:
							recv_datas = s.recv(BUFSIZ)
						else:
							recv_datas = s.recv(filesize)
						fileoper.write(recv_datas)
						rfilesize=rfilesize-len(recv_datas)
						pert=100-100*rfilesize/filesize
						print "\r "+str(pert)+"%",
						#sys.stdout.write("\r"+str(pert)+"%",)
						#sys.stdout.flush()
						if rfilesize<=0:
							break
						time.sleep(0.001)
					print ""
					
					fileoper.flush()
					fileoper.close()
					logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
					print logdate+",文件下载成功,已保存到"+localfile
					s.sendall('__EndForGetFile__')
					s.close()
					lag=0
			time.sleep(0.1)

 
if __name__ == '__main__':
	#Default 127.0.0.1
	#HOST = str(raw_input('Server IP: ')).strip()
	#Defautl 9889
	#PORT = int(raw_input('Server PORT: '))
	#ADDR = (HOST,PORT)
	#ADDR = ('127.0.0.1',9899)
	BUFSIZ = 8192

	length = len(sys.argv)
	
	if length<5:
		strs='''
				wrong para,please input host port argv value
				just like:
				LightCamPy lc_manager.py 127.0.0.1 8640 comd hostname 
				LightCamPy lc_manager.py 127.0.0.1 8640 get "/tmp/remotefile /tmp/localfile" 
				LightCamPy lc_manager.py 127.0.0.1 8640 put "/tmp/localfile /tmp/remotefile" 
				LightCamPy lc_manager.py 127.0.0.1 8640 ecmd mondb1__hostname 
				LightCamPy lc_manager.py 127.0.0.1 8640 ecmd mondb1__InitAgentList 
				LightCamPy lc_manager.py 127.0.0.1 8640 eget agentname__localfile__remotefile 
				LightCamPy lc_manager.py 127.0.0.1 8640 eput agentname__localfile__remotefile 
		'''
		print strs
		exit(0)
	
	ADDR=(sys.argv[1],int(sys.argv[2]))
	argv=sys.argv[3]
	value=sys.argv[4]
	
	s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
	try:
		s.connect(ADDR)
	except Exception:
		excinfo=traceback.format_exc()
		print excinfo
		exit(0)
	switch(argv,value)
